<?php
/**
 * installation script
 *
 * @author Mario Schillermann <info@rockit-flash.com>
 * @encoding UTF-8 äöüßÖÄÜ
 * @copyright © 2011 Mario Schillermann (info@rockit-flash.com)
 * @package
 * @subpackage
 * @version 1.0.0
 * @phpVersion >=5.3
 * @todo create Favorite Link, Save the entered data
 */

/**
 * Extracting Zip File
 *
 * @param  string $filename
 * @param  string $path
 *
 * @return void
 */
function unzip($filename, $path) {

    if (function_exists('zip_open')) {

        $zipPath = dirname(__FILE__) .DIRECTORY_SEPARATOR . $path .DIRECTORY_SEPARATOR . $filename;

	if (file_exists($zipPath) && ($zip = zip_open($zipPath)) && gettype($zip) == 'resource') {

            while($zip_entry = zip_read($zip)) {
                $file_name = zip_entry_name($zip_entry);
                $file_size = zip_entry_filesize($zip_entry);
                $comp_meth = zip_entry_compressionmethod($zip_entry);

                if (zip_entry_open($zip, $zip_entry, 'rb')) {
                    $buffer = zip_entry_read($zip_entry, $file_size);

                    if (preg_match('/\/$/', $file_name) &&
                        ($comp_meth == 'stored')
                       ) {
                        if (!is_dir($path . $file_name))
                            @mkdir($path . $file_name, 0777);
                    } else {
                        $fp = fopen($path . $file_name, 'wb');
                        fwrite($fp, $buffer);
                        fclose($fp);
                    }
                    zip_entry_close($zip_entry);
                }
            }
            zip_close($zip);
	} else {
            throw new Exception (
                'Konnte die Datei ' . $filename . ' nicht öffnen!'
            );

        }
    } else {
        throw new Exception (
            'Bitte aktivieren Sie in der php.ini die Extensions ' .
            'php_zip.dll in dem sie das Semikolon vor dieser Zeile ;' .
            'extension=php_zip.dll entfernen.'
        );
    }
}

/**
 * Gets contents of any webside by an URI.
 *
 * @param  string $uri
 *
 * @return string filecontent
 */
function getContentByUri($uri) {

    $uriElem = parse_url ( $uri );
    $fp = @fsockopen ( $uriElem ['host'], 80, $errno, $errstr, 10 );

    if (!$fp) {
        throw new Exception ( "Could not create socket: '" . $errnstr . "' (" . $errno . ")." );
    }

    $request = "GET " . $uriElem ['path'] . (isset ( $uriElem ['query'] ) ?
               "?" . $uriElem ['query'] : "") . " HTTP/1.1\r\n";
    $request .= "Host: " . $uriElem ['host'] . "\r\n";
    $request .= "Connection: Close\r\n\r\n";

    fwrite ( $fp, $request );
    $response = "";
    while ( ! feof ( $fp ) ) {
        $response .= fgets ( $fp, 128 );
    }
    fclose ( $fp );

    // split headers from data
    $responseSplit = explode ( "\r\n\r\n", $response, 2 );

    return $responseSplit [1];
}
/**
 * install script
 *
 * @param string $filename
 * @param string $basePicPath
 *
 * @return void
 */
function installScript($zipFile, $basePicPath) {

    $servername = $zipFile['path'] . $zipFile['file'];

    try {
        if (is_writable($zipFile['target'])) {
            $current = getContentByUri($servername);
            if (file_put_contents($zipFile['target'] . $zipFile['file'], $current)) {
                unzip($zipFile['file'], $zipFile['target']);
                unlink($zipFile['target'] . $zipFile['file']);
            }
        } else {
            throw new Exception ( "Keine Schreibrechte auf dem Server!" );
        }
    } catch (Exception $e) {
        unlink($zipFile['file']);
        return '<p class="error">
                    <img src="' . $basePicPath . 'installError.png"/>' .
                    $e->getMessage().
               '</p>
               <p class="send">
                   <input type="button"
                          value="Installation wiederholen"
                          onClick="window.location.href=\'?step=1\'"/>
               </p>';
    }
}

$step = (int)$_GET['step'];
$css = array();
$adminPath = 'http://localhost';
$basePicPath = 'http://rockitflash-cms.googlecode.com/files/';

switch ($step) {

    case 1:
        $css['distance'] = '-6em';
        $css['window']['width'] = '33em';
        $content = '<img class="logo" src="' . $basePicPath . 'installLogo.png"/>';
        $zipFiles = array();

        $zipFiles[0]['path'] = 'http://rockitflash-cms.googlecode.com/files/';
        $zipFiles[0]['file'] = 'cms-1.0.0.zip';
        $zipFiles[0]['target'] = './';

        $zipFiles[1]['path'] = 'http://framework.zend.com/releases/ZendFramework-1.10.8/';
        $zipFiles[1]['file'] = 'ZendFramework-1.10.8-minimal.zip';
        $zipFiles[1]['target'] = './library/';

        foreach($zipFiles as $zipFile) {
            if(($tmp = installScript($zipFile, $basePicPath))) {
                break;
            }
        }
        if($tmp) {
            $content .= $tmp;
        } else {
            $content .= '<p class="succses">
                             <img src="' . $basePicPath . 'installSuccsess.png"/>
                             Installation abgeschlossen.
                         </p>
                         <p class="send">
                             <input type="button"
                                    value="CMS einrichten"
                                    onClick="window.location.href=\'/de/admin/g4Z83j\'"/>
                         </p>';
        }
        break;

    default:
        $css['distance'] = '-8em';
        $css['window']['width'] = '33em';
        $content = '<img width="32" height="32" src="loading.gif" style="display:none;"/>
                    <img class="logo" src="' . $basePicPath . 'installLogo.png"/>
                    <p>Klicke auf <b>CMS installieren</b>.</p>
                    <p>Die benötigten Daten werden vom Server geladen.</p>
                    <p>Es wird keinerlei Haftung für etwaige Schäden übernommen.</p>
                    <p class="send">
                        <input type="button"
                               value="CMS installieren"
                               onClick="loading();"/>
                    </p>';
}
?>

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style type="text/css">
            * {
                margin:0;
                padding:0;
            }

            html, body {
                height:100%;
            }

            body {
                background-image: url('<?php echo $basePicPath;?>installBackground.jpg');
                color:#630;
                font:100.01%/1.4 sans-serif;
                text-align:center; /* horizontal centering for IE Win quirks */
            }

            #distance {
                width:1px;
                height:50%;
                background-color:#fc6;
                margin-bottom:<?php echo $css['distance'];?>; /* half of container's height */
                float:left;
            }

            #window {
                margin:0 auto;
                position:relative; /* puts container in front of distance */
                text-align:left;
                width: <?php echo $css['window']['width'];?>;
                clear:left;
                background-color:#FFFFFF;
                border:1px solid #c93;
                border-color:#8d8d8d;
                border-radius: 10px 10px;
                -moz-box-shadow: 5px 5px 5px #888888;
                -webkit-box-shadow: 5px 5px 5px #888888;
                box-shadow: 5px 5px 5px #888888;
            }
            .title {
                text-align: center;
                background-image: url('<?php echo $basePicPath;?>installTitle.jpg');
                border-bottom: solid 1px #8d8d8d;
                color: #666666;
                border-top-left-radius: 10px 10px;
                border-top-right-radius: 10px 10px;
            }
            #content {
                color: #000000;
                padding: 16px;
                text-align: center;
            }
            .send {
                text-align: center;
                padding: 6px;
                margin-top: 25px;
                border-top: solid 1px #CCCCCC;
            }
            .error {
                color: #ff0000;
            }
            .succses {
                color: #009933;
            }
            .succses, .error {
                margin-top: 10px;
            }
            .error img, .succses img {
                margin-right: 4px;
            }
            label {
                width: 8em;
                display: block;
                float: left;
                text-align: left;
            }
            fieldset {
                border: 1px solid #CCCCCC;
                padding: 10px;
                margin-top: 12px;
                margin-bottom: 12px;
            }
            .formField {
                width: 204px;
            }
        </style>
        <script type="text/javascript">
            function loading() {
                var content = document.getElementById("content");
                content.innerHTML = '<img class="logo" src="<?php echo $basePicPath;?>installLogo.png"/><p><img width="32" height="32" src="<?php echo $basePicPath?>loading.gif"/></p><p>RockitFlashCMS wird installiert...</p>';
                window.location.href='?step=1';
            }
            function addBookmark() {
                window.sidebar.addPanel('title', 'http://localhost','');
            }
        </script>
    </head>
    <body>
        <div id="distance"></div>
        <div id="window">
            <div class="title">Setup</div>
            <div id="content">
                <?php echo $content;?>
            </div>
        </div>
    </body>
</html>